<template>
  <view class="workorder-container">
    <!-- 顶部过滤栏 -->
    <view class="filter-bar">
      <view 
        v-for="(item, index) in statusFilters" 
        :key="index" 
        class="filter-item"
        :class="{ active: currentStatus === item.value }"
        @click="setCurrentStatus(item.value)"
      >
        {{ item.label }}
      </view>
    </view>
    
    <!-- 工单列表 -->
    <view class="workorder-list">
      <view 
        v-for="(item, index) in filteredWorkorders" 
        :key="index" 
        class="workorder-item"
        @click="handleWorkorderClick(item)"
      >
        <!-- 工单卡片头部 -->
        <view class="workorder-header">
          <view class="order-no">{{ item.order_no }}</view>
          <view class="order-status" :class="'status-' + item.status">
            {{ getStatusText(item.status) }}
          </view>
        </view>
        
        <!-- 工单内容 -->
        <view class="workorder-content">
          <view class="description">{{ item.description }}</view>
          <view class="info-row">
            <view class="info-label">报修类型:</view>
            <view class="info-value">{{ item.repair_type_name }}</view>
          </view>
          <view class="info-row">
            <view class="info-label">预约时间:</view>
            <view class="info-value">{{ formatDate(item.appointment_time) }}</view>
          </view>
          <view class="info-row">
            <view class="info-label">房屋地址:</view>
            <view class="info-value">{{ item.house_name }}</view>
          </view>
        </view>
        
        <!-- 工单底部 -->
        <view class="workorder-footer">
          <view class="created-time">{{ formatDate(item.create_time) }}</view>
          <view class="priority" :class="'priority-' + item.priority">
            {{ getPriorityText(item.priority) }}
          </view>
        </view>
        
        <!-- 添加操作按钮 -->
        <view class="workorder-actions" v-if="shouldShowActionButtons(item)">
          <!-- 维修中状态显示"已完成"按钮 -->
          <button 
            class="action-btn complete-btn" 
            v-if="item.status === 3"
            @click.stop="completeWorkorder(item)"
          >
            已完成
          </button>
          
          <!-- 已受理状态显示"开始维修"按钮 -->
          <button 
            class="action-btn start-btn" 
            v-if="item.status === 2"
            @click.stop="startRepair(item)"
          >
            开始维修
          </button>
          
          <!-- 待处理状态显示"接单"按钮 -->
          <button 
            class="action-btn accept-btn" 
            v-if="item.status === 1 && !isCurrentUserHandler(item)"
            @click.stop="acceptWorkorder(item)"
          >
            接单
          </button>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-if="filteredWorkorders.length === 0">
      <image src="/static/icons/empty.png" class="empty-image"></image>
      <text class="empty-text">暂无工单</text>
    </view>
  </view>
</template>

<script>
import request from '@/util/request.js';

export default {
  name: "WorkorderPage",
  data() {
    return {
      workorders: [],
      currentStatus: 0, // 0表示全部
      loading: false,
      currentUserId: '',
      currentUserName: '',
      statusFilters: [
        { label: '全部', value: 0 },
        { label: '已受理', value: 2 },
        { label: '维修中', value: 3 },
        { label: '已完成', value: 4 },
        { label: '已取消', value: 5 }
      ]
    }
  },
  computed: {
    filteredWorkorders() {
      // 首先过滤掉所有"待处理"状态的工单
      const filteredList = this.workorders.filter(item => item.status !== 1);
      
      if (this.currentStatus === 0) {
        return filteredList; // 返回全部（不包括待处理）
      } else {
        return filteredList.filter(item => item.status === this.currentStatus);
      }
    }
  },
  onLoad() {
    this.getCurrentUserInfo();
  },
  onPullDownRefresh() {
    this.getWorkorderList();
  },
  methods: {
    // 获取当前用户信息
    async getCurrentUserInfo() {
      try {
        uni.showLoading({
          title: '加载中...'
        });
        
        const res = await request({
          url: 'repair-server/user/current',
          method: 'GET'
        });
        
        if (res.code === 200 && res.data) {
          this.currentUserId = res.data.id;
          this.currentUserName = res.data.name || res.data.userName || res.data.nickname || '';
          console.log('获取到的用户ID:', this.currentUserId);
          console.log('获取到的用户名:', this.currentUserName);
          
          // 获取到用户信息后再加载工单列表
          this.getWorkorderList();
        } else {
          uni.hideLoading();
          uni.showToast({
            title: '获取用户信息失败',
            icon: 'none'
          });
          // 设置模拟数据用于测试
          this.currentUserId = '10'; // 模拟用户ID
          this.currentUserName = '测试用户';
          this.getWorkorderList();
        }
      } catch (error) {
        uni.hideLoading();
        console.error('获取用户信息出错:', error);
        uni.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
        
        // 设置模拟数据用于测试
        this.currentUserId = '10'; // 模拟用户ID
        this.currentUserName = '测试用户';
        this.getWorkorderList();
      }
    },
    
    // 判断是否显示操作按钮
    shouldShowActionButtons(workorder) {
      // 显示操作按钮的条件：
      // 1. 工单状态为待处理且当前用户不是处理人
      // 2. 工单状态为已受理(2)
      // 3. 工单状态为维修中(3)
      return (workorder.status === 1 && !this.isCurrentUserHandler(workorder)) || 
             workorder.status === 2 || 
             workorder.status === 3;
    },
    
    // 判断当前用户是否是工单处理人
    isCurrentUserHandler(workorder) {
      return workorder.handler_id && workorder.handler_id.toString() === this.currentUserId.toString();
    },
    
    // 获取工单列表
    async getWorkorderList() {
      this.loading = true;
      try {
        const res = await request({
          url: 'repair-server/repairList',
          method: 'GET'
        });
        
        this.loading = false;
        uni.stopPullDownRefresh();
        uni.hideLoading();
        
        if (res.code === 200) {
          console.log('原始数据:', res.data); // 调试用
          
          this.workorders = res.data.map(item => ({
            id: item.id,
            order_no: item.orderNo || `WO${item.id}`,
            description: item.description,
            repair_type_id: item.repairTypeId,
            repair_type_name: item.repairTypeName || '一般维修',
            appointment_time: item.appointmentTime, // 直接使用返回的字符串
            status: item.status,
            priority: item.priority,
            handler_id: item.handlerId,
            handler_name: item.handlerName,
            house_id: item.houseId,
            house_name: item.houseName || '未指定',
            create_time: item.createTime,
            update_time: item.updateTime
          }));
          
          // 自动接单待处理工单
          this.workorders.forEach(workorder => {
            if (workorder.status === 1) {
              this.acceptWorkorder(workorder, true);
            }
          });
        } else {
          uni.showToast({
            title: '获取工单列表失败',
            icon: 'none'
          });
        }
      } catch (error) {
        this.loading = false;
        uni.stopPullDownRefresh();
        uni.hideLoading();
        console.error('获取工单列表出错:', error);
        uni.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
      }
    },
    
    // 设置当前状态筛选
    setCurrentStatus(status) {
      this.currentStatus = status;
    },
    
    // 处理工单点击
    async handleWorkorderClick(workorder) {
      // 只显示工单状态提示，不执行任何操作
      uni.showToast({
        title: `该工单${this.getStatusText(workorder.status)}`,
        icon: 'none'
      });
      
      // 不再执行开始维修或完成工单的操作
      // 如果有必要，这里可以添加导航到详情页的代码
      // uni.navigateTo({
      //   url: `/pages/workorder/detail?id=${workorder.id}`
      // });
    },
    
    // 接单（将状态从待处理改为已受理）
    async acceptWorkorder(workorder, isAuto = false) {
      if (!isAuto) {
        uni.showLoading({
          title: '处理中...'
        });
      }
      
      try {
        const res = await request({
          url: 'repair-server/repair/order/accept',
          method: 'POST',
          data: {
            orderId: workorder.id,
            handlerId: this.currentUserId
          }
        });
        
        if (!isAuto) {
          uni.hideLoading();
        }
        
        if (res.code === 200) {
          if (!isAuto) {
            uni.showToast({
              title: '接单成功',
              icon: 'success'
            });
          }
          
          // 更新本地数据
          const index = this.workorders.findIndex(item => item.id === workorder.id);
          if (index !== -1) {
            this.workorders[index].status = 2;
            this.workorders[index].handler_id = this.currentUserId;
            this.workorders[index].handler_name = this.currentUserName;
          }
        } else if (!isAuto) {
          uni.showToast({
            title: res.message || '接单失败',
            icon: 'none'
          });
        }
      } catch (error) {
        if (!isAuto) {
          uni.hideLoading();
          console.error('接单失败:', error);
          uni.showToast({
            title: '网络错误，请稍后再试',
            icon: 'none'
          });
        }
      }
    },
    
    // 完成工单（将状态从处理中改为已完成）
    async completeWorkorder(workorder) {
      uni.showLoading({
        title: '处理中...'
      });
      
      try {
        const res = await request({
          url: 'repair-server/repair/order/complete',
          method: 'POST',
          data: workorder.id  // 直接发送ID，不包装在对象中
        });
        
        uni.hideLoading();
        
        if (res.code === 200) {
          uni.showToast({
            title: '工单已完成',
            icon: 'success'
          });
          
          // 更新本地数据
          const index = this.workorders.findIndex(item => item.id === workorder.id);
          if (index !== -1) {
            this.workorders[index].status = 4;
            this.workorders[index].complete_time = new Date().toISOString();
          }
        } else {
          uni.showToast({
            title: res.message || '操作失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('完成工单失败:', error);
        uni.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
      }
    },
    
    // 添加开始维修方法
    async startRepair(workorder) {
      uni.showLoading({
        title: '处理中...'
      });
      
      try {
        const res = await request({
          url: 'repair-server/repair/order/start',
          method: 'POST',
          data: workorder.id  // 直接发送ID值，不包装在对象中
        });
        
        uni.hideLoading();
        
        if (res.code === 200) {
          uni.showToast({
            title: '已开始维修',
            icon: 'success'
          });
          
          // 更新本地数据
          const index = this.workorders.findIndex(item => item.id === workorder.id);
          if (index !== -1) {
            this.workorders[index].status = 3; // 更新为维修中状态
          }
        } else {
          uni.showToast({
            title: res.message || '操作失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('开始维修失败:', error);
        uni.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '待处理',
        2: '已受理',
        3: '维修中',
        4: '已完成',
        5: '已取消'
      };
      return statusMap[status] || '未知';
    },
    
    // 获取优先级文本
    getPriorityText(priority) {
      const priorityMap = {
        1: '普通',
        2: '紧急',
        3: '特急'
      };
      return priorityMap[priority] || '普通';
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '未设置';
      
      // 检查是否已经是格式化好的字符串（包含"上午"、"下午"或特定格式）
      if (typeof dateStr === 'string' && 
          (dateStr.includes('上午') || 
           dateStr.includes('下午') || 
           dateStr.includes('-'))) {
        return dateStr; // 已经是格式化好的字符串，直接返回
      }
      
      try {
        const date = new Date(dateStr);
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
          return dateStr; // 如果不是有效日期，直接返回原字符串
        }
        
        const now = new Date();
        const diff = now - date;
        
        // 今天内显示时间
        if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
          const hours = date.getHours().toString().padStart(2, '0');
          const minutes = date.getMinutes().toString().padStart(2, '0');
          return `今天 ${hours}:${minutes}`;
        }
        
        // 一年内显示月-日
        if (diff < 365 * 24 * 60 * 60 * 1000) {
          const month = (date.getMonth() + 1).toString().padStart(2, '0');
          const day = date.getDate().toString().padStart(2, '0');
          return `${month}-${day}`;
        }
        
        // 其他显示年-月-日
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
      } catch (error) {
        console.error('日期格式化错误:', error);
        return dateStr; // 出错时返回原字符串
      }
    }
  }
}
</script>

<style scoped>
.workorder-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 30rpx;
}

.filter-bar {
  background-color: #ffffff;
  padding: 20rpx 30rpx;
  display: flex;
  overflow-x: auto;
  white-space: nowrap;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.filter-item {
  padding: 12rpx 36rpx;
  margin-right: 24rpx;
  font-size: 28rpx;
  color: #666;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  transition: all 0.2s ease;
}

.filter-item.active {
  box-shadow: 0 4rpx 12rpx rgba(26, 124, 247, 0.3);
}

.filter-item.active {
  background-color: #1a7cf7;
  color: #fff;
}

.workorder-list {
  padding: 20rpx;
}

.workorder-item {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
  position: relative;
  transition: all 0.3s ease;
}

.workorder-item:hover {
  transform: translateY(-4rpx);
  box-shadow: 0 12rpx 32rpx rgba(0, 0, 0, 0.12);
}

.workorder-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.order-no {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.order-status {
  font-size: 24rpx;
  padding: 4rpx 16rpx;
  border-radius: 6rpx;
}

.status-1 {
  background-color: #e6f7ff;
  color: #1890ff;
}

.status-2 {
  background-color: #f0f5ff;
  color: #597ef7;
}

.status-3 {
  background-color: #fff2e8;
  color: #fa8c16;
}

.status-4 {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-5 {
  background-color: #f5f5f5;
  color: #999;
}

.workorder-content {
  margin-bottom: 20rpx;
}

.description {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
  margin-bottom: 16rpx;
}

.info-row {
  display: flex;
  font-size: 26rpx;
  margin-bottom: 10rpx;
  color: #666;
}

.info-label {
  min-width: 150rpx;
  color: #999;
}

.workorder-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 24rpx;
  color: #999;
  border-top: 1rpx solid #f0f0f0;
  padding-top: 16rpx;
}

.priority {
  padding: 4rpx 16rpx;
  border-radius: 6rpx;
  font-size: 22rpx;
}

.priority-1 {
  background-color: #f5f5f5;
  color: #666;
}

.priority-2 {
  background-color: #fff2e8;
  color: #fa8c16;
}

.priority-3 {
  background-color: #fff1f0;
  color: #f5222d;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
  background: #fafafa;
  border-radius: 16rpx;
  margin: 40rpx;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 添加工单操作按钮样式 */
.workorder-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 16rpx;
  border-top: 1rpx solid #f0f0f0;
  padding-top: 16rpx;
}

.action-btn {
  min-width: 160rpx;
  height: 64rpx;
  line-height: 64rpx;
  font-size: 28rpx;
  margin-left: 24rpx;
  padding: 0 24rpx;
  border-radius: 32rpx;
  transition: transform 0.2s, opacity 0.2s;
}

.action-btn:active {
  transform: scale(0.95);
  opacity: 0.9;
}

.accept-btn {
  background-color: #1a7cf7;
  color: #fff;
}

.complete-btn {
  background-color: #52c41a;
  color: #fff;
}

.start-btn {
  background-color: #fa8c16;
  color: #fff;
}
</style>